﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace testMongodb2017年8月21日
{
    public class Record
    {
        /// <summary>
        /// The Customer Id
        /// </summary>
        public int cusid { get; set; }

        /// <summary>
        /// The Price
        /// </summary>
        public int price { get; set; }
    }
    public class MongoDBHelper
    {
        /// <summary>  
        /// Get the specific db instance  
        /// </summary>  
        /// <param name="connectionString">The connect string</param>  
        /// <param name="dbName">DB name</param>  
        /// <returns>The DB instance</returns>  
        public static MongoDatabase GetDatabase(string connectionString, string dbName)
        {
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            MongoDatabase database = server.GetDatabase(dbName);

            return database;
        }
    }
    class Program
    {/// <summary>  
        /// Insert test data to records collection in db  
        /// </summary>  
        /// <param name="records">The records instance</param>  
        static void InsertTestDataToRecords(MongoCollection<Record> records)
        {
            records.Insert<Record>(new Record() { cusid = 1, price = 15 });
            records.Insert<Record>(new Record() { cusid = 2, price = 30 });
            records.Insert<Record>(new Record() { cusid = 2, price = 45 });
            records.Insert<Record>(new Record() { cusid = 3, price = 45 });
            records.Insert<Record>(new Record() { cusid = 4, price = 5 });
            records.Insert<Record>(new Record() { cusid = 5, price = 65 });
            records.Insert<Record>(new Record() { cusid = 1, price = 10 });
            records.Insert<Record>(new Record() { cusid = 1, price = 30 });
            records.Insert<Record>(new Record() { cusid = 5, price = 30 });
            records.Insert<Record>(new Record() { cusid = 4, price = 100 });
            records.Insert<Record>(new Record() { cusid = 3, price = 10 });
        }  
        private static void Main(string[] args)
        {

            #region Test MongoDB Map-Reduce
            // Connection string format: mongodb://[username:password@][host][:port]/[database]  
            var connectionString = "mongodb://127.0.0.1:27017/admin";
            string dbName = "admin";
            var db = MongoDBHelper.GetDatabase(connectionString, dbName);
            var records = db.GetCollection<Record>("records");

            InsertTestDataToRecords(records);

            // Write map and reduce function  
            string mapFunction = @"function(){  
                                    emit(this.cusid, this.price);  
                                };";

            string reduceFunction = @"function(cusid, prices){  
                                    var total = 0;  
                                    total = Array.sum(prices);  
                                    return { sum: total };  
                                };";

            // Execute map-reduce method  
            var cusid_prices_results = records.MapReduce(mapFunction, reduceFunction);

            // Print results  
            Console.WriteLine("Print the results of executing MapReduce method:\r\n");
            foreach (var item in cusid_prices_results.GetResults())
            {
                Console.WriteLine(item.ToString());
            }

            Console.ReadKey();
            #endregion  
        }

        static void Main1(string[] args)
        {
            var server = new MongoServer(MongoServerSettings.FromUrl(new MongoUrl("mongodb://127.0.0.1:27017")));
            Console.WriteLine(server);
            Console.WriteLine(server.Settings);

            foreach (var databaseName in server.GetDatabaseNames())
            {
                var db = server.GetDatabase(databaseName);
            //    var r=db.Eval(new BsonJavaScript("function(){return db.lo.ensureIndex({\"name\":1,\"background\":true});}"));
             var r=db.Eval(new BsonJavaScript(@"
db.t.insert(
　　{
　　　　""_id"":""log"",
　　　　""value"":function(msg,level)
　　　　　　　　{
　　　　　　　　　　var levels=[""DEBUG"",""WARN"",""ERROR"",""PATAL""];
　　　　　　　　　　level=level?level:0;
　　　　　　　　　　var now= new Date();
　　　　　　　　　　print( now +"" ""+ levels[level]+msg);
　　　　　　　　}
　　}
)
            "));
           Console.WriteLine(r);
                Console.WriteLine(db);
            }
          //  for (int i = 0; i < 100; i++)
          //      db.Eval(new BsonJavaScript("function(){return db.lo.insert({\"name\":\"哈哈哈\"});}"));
              
          
            Console.Read();
        }
    }
}
